<template>
  <div class="sales-list-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h2 class="page-title">羊只销售记录</h2>
        <p class="page-description">查看和管理羊只销售记录</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="refreshData" :icon="Refresh" :loading="loading">
          刷新
        </el-button>
        <el-button type="success" @click="goToAddPage" :icon="Plus">
          新增记录
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <el-card class="search-card">
        <el-form :model="searchForm" :inline="true" class="search-form">
          <el-form-item label="耳号">
            <el-input 
              v-model="searchForm.earNumber" 
              placeholder="请输入耳号" 
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="品种">
            <el-input 
              v-model="searchForm.variety" 
              placeholder="请输入品种" 
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="栋舍">
            <el-select 
              v-model="searchForm.building" 
              placeholder="请选择栋舍" 
              clearable
              style="width: 150px"
            >
              <el-option label="大羊舍" value="大羊舍" />
              <el-option label="配种舍" value="配种舍" />
              <el-option label="采购羊栋舍" value="采购羊栋舍" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :icon="Search">
              搜索
            </el-button>
            <el-button @click="resetSearch" :icon="RefreshRight">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-card class="table-card">
        <template #header>
          <div class="table-header">
            <span class="table-title">销售记录列表</span>
            <div class="table-info">
              <span class="record-count">共 {{ totalCount }} 条记录</span>
            </div>
          </div>
        </template>

        <el-table 
          :data="tableData" 
          v-loading="loading"
          stripe
          border
          style="width: 100%"
          empty-text="暂无数据"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="salesId" label="ID" width="80" align="center" />
          <el-table-column prop="earNumber" label="耳号" width="120" align="center" />
          <el-table-column prop="variety" label="品种" width="120" align="center" />
          <el-table-column prop="sex" label="性别" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="row.sex === '公' ? 'primary' : 'success'">
                {{ row.sex }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="类型" width="100" align="center" />
          <el-table-column prop="building" label="栋舍" width="120" align="center" />
          <el-table-column prop="column" label="栏位" width="100" align="center" />
          <el-table-column prop="birtdate" label="出生日期" width="180" align="center">
            <template #default="{ row }">
              {{ formatDate(row.birtdate) }}
            </template>
          </el-table-column>
          <el-table-column prop="birthweight" label="出生重" width="100" align="center" />
          <el-table-column prop="clinch" label="成交价" width="100" align="center" />
          <el-table-column label="操作" width="350" align="center" fixed="right">
            <template #default="{ row }">
              <el-button 
                type="primary" 
                size="small" 
                @click="viewDetail(row)"
                :icon="View"
              >
                查看
              </el-button>
              <el-button 
                type="warning" 
                size="small" 
                @click="editRecord(row)"
                :icon="Edit"
              >
                编辑
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="deleteRecord(row)"
                :icon="Delete"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="pagination.pageIndex"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="totalCount"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 批量操作 -->
    <div class="batch-actions" v-if="selectedRows.length > 0">
      <el-card class="batch-card">
        <div class="batch-content">
          <span class="batch-info">已选择 {{ selectedRows.length }} 条记录</span>
          <div class="batch-buttons">
            <el-button type="danger" @click="batchDelete" :icon="Delete">
              批量删除
            </el-button>
            <el-button @click="clearSelection" :icon="Close">
              取消选择
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 详情对话框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="销售记录详情" 
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="detail-content" v-if="currentRecord">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="记录ID">{{ currentRecord.salesId }}</el-descriptions-item>
          <el-descriptions-item label="耳号">{{ currentRecord.earNumber }}</el-descriptions-item>
          <el-descriptions-item label="品种">{{ currentRecord.variety }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ currentRecord.sex }}</el-descriptions-item>
          <el-descriptions-item label="类型">{{ currentRecord.type }}</el-descriptions-item>
          <el-descriptions-item label="繁殖">{{ currentRecord.reproduction }}</el-descriptions-item>
          <el-descriptions-item label="栋舍">{{ currentRecord.building }}</el-descriptions-item>
          <el-descriptions-item label="栏位">{{ currentRecord.column }}</el-descriptions-item>
          <el-descriptions-item label="出生日期">{{ formatDate(currentRecord.birtdate) }}</el-descriptions-item>
          <el-descriptions-item label="出生重">{{ currentRecord.birthweight }}</el-descriptions-item>
          <el-descriptions-item label="断奶">{{ currentRecord.weaning }}</el-descriptions-item>
          <el-descriptions-item label="父母">{{ currentRecord.parents }}</el-descriptions-item>
          <el-descriptions-item label="成交价">{{ currentRecord.clinch }}</el-descriptions-item>
          <el-descriptions-item label="定价">{{ currentRecord.pricing }}</el-descriptions-item>
          <el-descriptions-item label="折扣">{{ currentRecord.discount }}</el-descriptions-item>
          <el-descriptions-item label="等级">{{ currentRecord.level }}</el-descriptions-item>
          <el-descriptions-item label="月龄" :span="2">{{ currentRecord.monthber }}</el-descriptions-item>
          <el-descriptions-item label="月天数" :span="2">{{ currentRecord.monthsday }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="currentRecord && editRecord(currentRecord)">编辑</el-button>
      </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog 
      v-model="editDialogVisible" 
      title="编辑销售记录" 
      width="900px"
      :close-on-click-modal="false"
    >
      <el-form 
        :model="editForm" 
        :rules="editRules" 
        ref="editFormRef"
        label-width="120px"
      >
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="记录ID" prop="salesId">
              <el-input v-model="editForm.salesId" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="耳号" prop="earNumber">
              <el-input v-model="editForm.earNumber" placeholder="请输入耳号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="品种" prop="variety">
              <el-input v-model="editForm.variety" placeholder="请输入品种" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="editForm.sex" placeholder="请选择性别" style="width: 100%">
                <el-option label="公" value="公" />
                <el-option label="母" value="母" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <el-input v-model="editForm.type" placeholder="请输入类型" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="繁殖" prop="reproduction">
              <el-input v-model="editForm.reproduction" placeholder="请输入繁殖" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="栋舍" prop="building">
              <el-select v-model="editForm.building" placeholder="请选择栋舍" style="width: 100%">
                <el-option label="大羊舍" value="大羊舍" />
                <el-option label="配种舍" value="配种舍" />
                <el-option label="采购羊栋舍" value="采购羊栋舍" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="栏位" prop="column">
              <el-input v-model="editForm.column" placeholder="请输入栏位" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birtdate">
              <el-date-picker 
                v-model="editForm.birtdate" 
                type="datetime" 
                placeholder="选择出生日期时间"
                format="YYYY-MM-DD HH:mm:ss" 
                value-format="YYYY-MM-DDTHH:mm:ss"
                style="width: 100%" 
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生重" prop="birthweight">
              <el-input v-model="editForm.birthweight" placeholder="请输入出生重" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="断奶" prop="weaning">
              <el-input v-model="editForm.weaning" placeholder="请输入断奶" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="父母" prop="parents">
              <el-input v-model="editForm.parents" placeholder="请输入父母" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="成交价" prop="clinch">
              <el-input v-model="editForm.clinch" placeholder="请输入成交价" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="定价" prop="pricing">
              <el-input v-model="editForm.pricing" placeholder="请输入定价" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="折扣" prop="discount">
              <el-input v-model="editForm.discount" placeholder="请输入折扣" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="等级" prop="level">
              <el-input v-model="editForm.level" placeholder="请输入等级" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="月龄" prop="monthber">
              <el-input v-model="editForm.monthber" placeholder="请输入月龄" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="月天数" prop="monthsday">
              <el-input v-model="editForm.monthsday" placeholder="请输入月天数" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit" :loading="editLoading">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Refresh, 
  Plus, 
  Search, 
  RefreshRight, 
  View, 
  Edit, 
  Delete, 
  Close 
} from '@element-plus/icons-vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

// 路由
const router = useRouter()

// 接口定义
interface SalesRecord {
  salesId: number
  earNumber: string
  clinch: string
  pricing: string
  discount: string
  level: string
  variety: string
  sex: string
  type: string
  reproduction: string
  building: string
  column: string
  birtdate: string
  birthweight: string
  weaning: string
  parents: string
  monthber: string
  monthsday: string
  isDeleted: boolean
}

interface ApiResponse {
  totalCount: number
  totalPage: number
  data: SalesRecord[]
}

// 响应式数据
const loading = ref(false)
const tableData = ref<SalesRecord[]>([])
const totalCount = ref(0)
const selectedRows = ref<SalesRecord[]>([])
const detailDialogVisible = ref(false)
const currentRecord = ref<SalesRecord | null>(null)

// 编辑相关数据
const editDialogVisible = ref(false)
const editLoading = ref(false)
const editFormRef = ref()

// 编辑表单
const editForm = reactive({
  salesId: 0,
  earNumber: '',
  clinch: '',
  pricing: '',
  discount: '',
  level: '',
  variety: '',
  sex: '',
  type: '',
  reproduction: '',
  building: '',
  column: '',
  birtdate: '',
  birthweight: '',
  weaning: '',
  parents: '',
  monthber: '',
  monthsday: ''
})

// 分页数据
const pagination = reactive({
  pageIndex: 1,
  pageSize: 10
})

// 搜索表单
const searchForm = reactive({
  earNumber: '',
  variety: '',
  building: ''
})

// 编辑表单验证规则
const editRules = {
  earNumber: [
    { required: true, message: '请输入耳号', trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true
    
    const params = {
      PageIndex: pagination.pageIndex,
      PageSize: pagination.pageSize,
      ...searchForm
    }
    
    console.log('请求参数:', params)
    
    const response = await axios.get('http://localhost:5052/api/Management/GetSales', { 
      params,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      timeout: 10000
    })
    
    console.log('API响应:', response.data)
    
    if (response.data) {
      const apiData: ApiResponse = response.data
      tableData.value = apiData.data || []
      totalCount.value = apiData.totalCount || 0
      
      // ElMessage.success(`成功加载 ${tableData.value.length} 条记录`)
    }
  } catch (error: any) {
    console.error('获取数据失败:', error)
    ElMessage.error(`获取数据失败: ${error.response?.data?.message || error.message}`)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.pageIndex = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    earNumber: '',
    variety: '',
    building: ''
  })
  pagination.pageIndex = 1
  fetchData()
}

// 刷新数据
const refreshData = () => {
  fetchData()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageIndex = 1
  fetchData()
}

const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page
  fetchData()
}

// 选择处理
const handleSelectionChange = (selection: SalesRecord[]) => {
  selectedRows.value = selection
}

const clearSelection = () => {
  selectedRows.value = []
}

// 查看详情
const viewDetail = (record: SalesRecord) => {
  currentRecord.value = record
  detailDialogVisible.value = true
}

// 编辑记录
const editRecord = async (record: SalesRecord) => {
  try {
    Object.assign(editForm, { ...record })
    editDialogVisible.value = true
  } catch (error) {
    ElMessage.error('打开编辑页面失败')
  }
}

// 保存编辑
const saveEdit = async () => {
  try {
    if (!editFormRef.value) return
    await editFormRef.value.validate()
    
    editLoading.value = true
    
    console.log('编辑数据:', editForm)
    
    const response = await axios.put('http://localhost:5008/api/Management/UpdateSales', editForm, {
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      timeout: 10000
    })
    
    console.log('编辑响应:', response)
    
    if (response.status === 200) {
      ElMessage.success('编辑成功')
      editDialogVisible.value = false
      fetchData()
    } else {
      ElMessage.error('编辑失败')
    }
  } catch (error: any) {
    console.error('编辑失败:', error)
    ElMessage.error(`编辑失败: ${error.response?.data?.message || error.message}`)
  } finally {
    editLoading.value = false
  }
}

// 删除记录
const deleteRecord = async (record: SalesRecord) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除耳号为 "${record.earNumber}" 的销售记录吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    console.log('删除记录ID:', record.salesId)
    
    const response = await axios.delete(`http://localhost:5008/api/Management/DeleteSales?SalesId=${record.salesId}`, {
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      timeout: 10000
    })
    
    console.log('删除响应:', response)
    
    if (response.status === 200) {
      ElMessage.success('删除成功')
      fetchData()
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error(`删除失败: ${error.response?.data?.message || error.message}`)
    }
  }
}

// 批量删除
const batchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const deletePromises = selectedRows.value.map(row => 
      axios.delete(`http://localhost:5008/api/Management/DeleteSales?SalesId=${row.salesId}`, {
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        timeout: 10000
      })
    )
    
    await Promise.all(deletePromises)
    
    ElMessage.success(`批量删除成功，共删除 ${selectedRows.value.length} 条记录`)
    selectedRows.value = []
    fetchData()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error(`批量删除失败: ${error.response?.data?.message || error.message}`)
    }
  }
}

// 跳转到新增页面
const goToAddPage = () => {
  router.push('/Sale')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.sales-list-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
}

.header-content h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.header-content p {
  margin: 0;
  opacity: 0.9;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-section {
  margin-bottom: 20px;
}

.search-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.table-section {
  margin-bottom: 20px;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.table-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.record-count {
  color: #666;
  font-size: 14px;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.batch-actions {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1000;
}

.batch-card {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.batch-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.batch-info {
  color: #666;
  font-size: 14px;
}

.batch-buttons {
  display: flex;
  gap: 8px;
}

.detail-content {
  padding: 16px 0;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .header-actions {
    width: 100%;
    justify-content: center;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 16px;
  }
  
  .table-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .batch-content {
    flex-direction: column;
    gap: 12px;
  }
}
</style>
